<!-- 参保人员列表页面 -->
<template>
  <div class="personnel-list-page">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input 
            v-model="searchForm.idCard" 
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="住院号">
          <el-input 
            v-model="searchForm.hospitalNumber" 
            placeholder="请输入住院号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="支付类型">
          <el-select 
            v-model="searchForm.paymentType" 
            placeholder="请选择支付类型"
            clearable
            style="width: 150px"
          >
            <el-option label="自费" value="自费" />
            <el-option label="医保" value="医保" />
          </el-select>
        </el-form-item>
        <el-form-item label="人员类型">
          <el-select 
            v-model="searchForm.personCategory" 
            placeholder="请选择人员类型"
            clearable
            style="width: 150px"
          >
            <el-option label="在职" value="在职" />
            <el-option label="退休" value="退休" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="hospitalNumber" label="住院号" width="120" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center" />
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="paymentType" label="支付类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.paymentType === '医保' ? 'success' : 'info'">
              {{ row.paymentType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="personCategory" label="人员类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.personCategory === '在职' ? 'primary' : 'warning'">
              {{ row.personCategory }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalLevel" label="医院等级" width="100" align="center" />
        <el-table-column prop="address" label="家庭住址" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="入院时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
              :icon="Edit"
            >
              修改
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handleView(row)"
              :icon="View"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 修改对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改参保人员信息"
      width="600px"
      :before-close="handleCloseEditDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="editForm.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="住院号" prop="hospitalNumber">
              <el-input v-model="editForm.hospitalNumber" placeholder="请输入住院号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number 
                v-model="editForm.age" 
                :min="0" 
                :max="150" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="editForm.birthDate"
                type="date"
                placeholder="请选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付类型" prop="paymentType">
              <el-select v-model="editForm.paymentType" placeholder="请选择支付类型">
                <el-option label="自费" value="自费" />
                <el-option label="医保" value="医保" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员类型" prop="personCategory">
              <el-select v-model="editForm.personCategory" placeholder="请选择人员类型">
                <el-option label="在职" value="在职" />
                <el-option label="退休" value="退休" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院等级" prop="hospitalLevel">
              <el-select v-model="editForm.hospitalLevel" placeholder="请选择医院等级">
                <el-option label="三级" value="三" />
                <el-option label="二级" value="二" />
                <el-option label="一级" value="一" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="家庭住址" prop="address">
          <el-input 
            v-model="editForm.address" 
            type="textarea" 
            :rows="3"
            placeholder="请输入家庭住址" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button type="primary" @click="handleConfirmEdit" :loading="saveLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="参保人员详细信息"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ viewData.idCard }}</el-descriptions-item>
        <el-descriptions-item label="住院号">{{ viewData.hospitalNumber }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewData.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewData.age }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatDate(viewData.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="支付类型">
          <el-tag :type="viewData.paymentType === '医保' ? 'success' : 'info'">
            {{ viewData.paymentType }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="人员类型">
          <el-tag :type="viewData.personCategory === '在职' ? 'primary' : 'warning'">
            {{ viewData.personCategory }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="医院等级">{{ viewData.hospitalLevel }}</el-descriptions-item>
        <el-descriptions-item label="家庭住址" :span="2">{{ viewData.address }}</el-descriptions-item>
        <el-descriptions-item label="入院时间">{{ formatDateTime(viewData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(viewData.updateTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Edit, View } from '@element-plus/icons-vue'
import { getPersonnelList, getPersonnelById, updatePersonnel } from '@/api/personnel'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const tableData = ref([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  idCard: '',
  hospitalNumber: '',
  paymentType: '',
  personCategory: '',
  hospitalLevel: ''
})

// 修改对话框
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = ref({})

// 修改表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  hospitalNumber: [
    { required: true, message: '请输入住院号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  paymentType: [
    { required: true, message: '请选择支付类型', trigger: 'change' }
  ]
}

// 查看对话框
const viewDialogVisible = ref(false)
const viewData = ref({})

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const response = await getPersonnelList(searchForm)
    if (response.flag) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取参保人员列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    idCard: '',
    hospitalNumber: '',
    paymentType: '',
    personCategory: '',
    hospitalLevel: ''
  })
  fetchData()
}

// 页码改变
const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  fetchData()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.pageNum = 1
  fetchData()
}

// 修改
const handleEdit = async (row) => {
  try {
    const response = await getPersonnelById(row.patientId)
    if (response.flag) {
      editForm.value = { ...response.data }
      editDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await getPersonnelById(row.patientId)
    if (response.flag) {
      viewData.value = response.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 确认修改
const handleConfirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    saveLoading.value = true
    
    const response = await updatePersonnel(editForm.value)
    if (response.flag) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(response.message || '修改失败')
    }
  } catch (error) {
    console.error('修改失败:', error)
    if (error !== false) { // 验证错误返回false，不显示错误消息
      ElMessage.error('修改失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 关闭修改对话框
const handleCloseEditDialog = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.personnel-list-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>
